//
//  YCLPhotoSelectorController.swift
//  03.照片选择器
//
//  Created by yaochunlin on 16/4/27.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

private let reuseIdentifier = "Cell"

class YCLPhotoSelectorController: UICollectionViewController {
    
    //存放选中的图片数组
    private var photos = [UIImage]()
    //可添加图片的最大数量
    private var maxPhotoCount = 6
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private let layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
    init(){
    
        super.init(collectionViewLayout: layout)
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置ui
        setupUI()
    }
    
//    private let ID = "identifier"
    
    private func setupUI() {
    
        //注册cell
        collectionView?.registerClass(YCLPhotoSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView?.backgroundColor = UIColor.whiteColor()
        
        layout.itemSize = CGSize.init(width: 80, height: 80)
        
        //设置内边距
        collectionView?.contentInset = UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    //MARK: collectionview的数据源方法
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return photos.count < maxPhotoCount ? photos.count + 1 : photos.count
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! YCLPhotoSelectorCell
        cell.backgroundColor = UIColor.brownColor()
        //设置代理
        cell.delegate = self
        
        //cell中显示photos中的图片
        if indexPath.item < photos.count {
            
            cell.image = photos[indexPath.item]
            
        }else{
        
            //设置加号按钮
            cell.setupAddBtn()
        }
        
        return cell
        
    }
    
}

//MARK: YCLPhotoSelectorCellDelegate代理方法
extension YCLPhotoSelectorController: YCLPhotoSelectorCellDelegate{

    func photoSelectorCelladdButtonClick(cell: YCLPhotoSelectorCell) {
        
//        print("添加按钮被点击")
        //系统相册
        let pickerVC = UIImagePickerController()
        
        //设置代理
        pickerVC.delegate = self
        
        presentViewController(pickerVC, animated: true, completion: nil)
        
    }
    
    func photoSelectorCelldeleteButtonClick(cell: YCLPhotoSelectorCell) {
        
//        print("删除按钮被点击")
        //获取点击的cell的索引
        let indexPath = collectionView?.indexPathForCell(cell)
        
        //将图片从数组中删除
        photos.removeAtIndex((indexPath?.item)!)
        
        //刷新界面
        collectionView?.reloadData()
        
        
    }
}

//MARK: UIImagePickerControllerDelegate UINavigationControllerDelegate代理方法
extension YCLPhotoSelectorController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{

    //选中图片时调用
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
//        print("image: \(image)")
        let newWidth:CGFloat = 300
        let newHeight = newWidth * image.size.height / image.size.width
        
        //异步等比例缩放图片
        image.ycl_AsyncDrawImage(CGSize.init(width: newWidth, height: newWidth)) { (image) in
            
            self.photos.append(image!)
            
            //刷新数据
            self.collectionView?.reloadData()
            
            //需要自己主动关闭相册控制器
            picker.dismissViewControllerAnimated(true, completion: nil)
        }
        
    }
}


//MARK: 自定义cell
//由于系统的cell无法满足需求，需要自定义cell

//点击cell要让控制器弹出系统相册,设置代理协议
protocol YCLPhotoSelectorCellDelegate: NSObjectProtocol {
    
    func photoSelectorCelladdButtonClick(cell: YCLPhotoSelectorCell)
    
    func photoSelectorCelldeleteButtonClick(cell: YCLPhotoSelectorCell)
}

class YCLPhotoSelectorCell: UICollectionViewCell {
    
    //给cell一个image属性
    var image: UIImage? {
     
        didSet{
        
            //将图片设置给加号按钮
            addButton.setImage(image, forState: UIControlState.Normal)
            
            //显示删除按钮
            deleteButton.hidden = false
        }
        
    }
    
    //设置加号按钮
    func setupAddBtn()  {
        
        addButton.setImage(UIImage.init(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        //隐藏删除按钮
        deleteButton.hidden = true
    }
    
    

    //设置代理属性
    weak var delegate: YCLPhotoSelectorCellDelegate?
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        //设置UI
        setupUI()
    }
    
    private func setupUI() {
    
        //添加子控件
        contentView.addSubview(addButton)
        contentView.addSubview(deleteButton)
        
        //设置约束
        addButton.translatesAutoresizingMaskIntoConstraints = false
        deleteButton.translatesAutoresizingMaskIntoConstraints = false
        
        let viewDicts = ["ab": addButton]
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: viewDicts))
        
        addConstraint(NSLayoutConstraint.init(item: deleteButton, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0))
        addConstraint(NSLayoutConstraint.init(item: deleteButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))


    }
    
    //MARK: 监听按钮的点击
    
    @objc private func addBtnClick() {
    
        //调用代理方法
        delegate?.photoSelectorCelladdButtonClick(self)
    }
    
    @objc private func deleteBtnClick() {
    
        delegate?.photoSelectorCelldeleteButtonClick(self)
    }
    
    //MARK: 懒加载控件
    //添加按钮
    private lazy var addButton: UIButton = {
    
        let btn = UIButton()
        
        btn.setImage(UIImage.init(named: "compose_pic_add"), forState: UIControlState.Normal)
        
        //设置图片的填充模式
        btn.imageView?.contentMode = UIViewContentMode.ScaleAspectFill//(?)
        
        //添加事件
        btn.addTarget(self, action: Selector("addBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    //删除按钮
    private lazy var deleteButton: UIButton = {
    
        let btn = UIButton()
        
        btn.setImage(UIImage.init(named: "compose_photo_close"), forState: UIControlState.Normal)
        
        btn.addTarget(self, action: Selector("deleteBtnClick"), forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
}
